package com.wondertek.poms.service.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.exception.MessageCodes;
import com.wondertek.poms.common.utils.LocalDateTimeUtils;
import com.wondertek.poms.common.utils.excel.ExportExcel;
import com.wondertek.poms.common.utils.excel.ImportExcel;
import com.wondertek.poms.common.utils.validate.ValidateFilter;
import com.wondertek.poms.common.vo.PageBean;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.service.ICpInfoService;
import com.wondertek.poms.dao.po.CpInfo;
import com.wondertek.poms.dao.pojo.CpInfoPojo;
import com.wondertek.poms.service.vo.CpInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author chenjijiang
 * @description
 */
@Api(value = "CpInfoController", description = "版权所属cp 接口")
@RestController
@RequestMapping(value = "/cp-info")
public class CpInfoController {

	@Autowired
	private ICpInfoService cpInfoService;

	/**
	 *
	 * @return 版权所属cp 全量列表
	 */
	@ApiOperation(value = "版权所属cp 全量", notes = "所有版权所属cp")
	@GetMapping("/list/all")
	public ResultBean getAll() {
		return ResultBean.ok(cpInfoService.findAll());
	}

	/**
	 * 分页查询
	 *
	 * @param cpInfoVo 查询条件
	 * @param page     页码
	 * @param rows     条数
	 * @param sidx     列名
	 * @param sord     升序/降序
	 * @return 版权所属cp 列表
	 */
	@ApiOperation(value = "版权所属cp 列表", notes = "查询版权所属cp")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "cpId", required = false),
			@ApiImplicitParam(name = "cpName", required = false)
	})
	@GetMapping("/list/by-id-name")
	public ResultBean list(CpInfoVo cpInfoVo,
						   @RequestParam(defaultValue = "1") int page,
						   @RequestParam(defaultValue = "20") int rows,
						   @RequestParam(defaultValue = "id") String sidx,
						   @RequestParam(defaultValue = "desc") String sord) {
		CpInfo cpInfo = new CpInfo();
		BeanUtils.copyProperties(cpInfoVo, cpInfo);
		Page<CpInfo> pages = cpInfoService.findAll(cpInfo, page, rows, sidx, sord);
		return PageBean.ok(pages.getTotalPages(), pages.getTotalElements(), pages.getContent());
	}

	/**
	 * 查看版权所属cp详情
	 *
	 * @param id 主键
	 * @return resultbean
	 */
	@ApiOperation(value = "版权所属cp 详情", notes = "查询版权所属cp详情")
	@ApiImplicitParam(name = "id", required = true, paramType = "query", dataType = "Long")
	@GetMapping(value = "/get")
	public ResultBean get(Long id) {
		CpInfo cpInfo = cpInfoService.get(id);
		return ResultBean.ok(cpInfo);
	}

	/**
	 * 编辑版权所属cp
	 *
	 * @param cpInfoVo 条目信息
	 * @return resultbean
	 */
	@ApiOperation(value = "版权所属cp 编辑", notes = "编辑版权所属cp")
	@PutMapping(value = "/edit")
	public ResultBean edit(@RequestBody CpInfoVo cpInfoVo) {
		List<String> messageList = ValidateFilter.getFilterMessage(cpInfoVo, Constants.VALIDATE_DEFAULT);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		if (isRepeat(cpInfoVo)) {
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		}

		CpInfo cpInfo = cpInfoService.findById(cpInfoVo.getId());

		if(!cpInfo.getCpId().equals(cpInfoVo.getCpId())){
			return ResultBean.error(MessageCodes.get(MessageCodes.M980502));
		}

		BeanUtils.copyProperties(cpInfoVo, cpInfo);
		cpInfoService.save(cpInfo);
		return ResultBean.ok();
	}

	/**
	 * 新增版权所属cp
	 *
	 * @param cpInfoVo 添加信息
	 * @return resultbean
	 */
	@ApiOperation(value = "版权所属cp 新增", notes = "新增版权所属cp")
	@PostMapping(value = "/add")
	public ResultBean add(@RequestBody CpInfoVo cpInfoVo) {
		//过滤
		List<String> messageList = ValidateFilter.getFilterMessage(cpInfoVo, Constants.VALIDATE_DEFAULT);
		if (!messageList.isEmpty()) {
			return ResultBean.error(messageList.toString());
		}
		//检查重复
		if (isRepeat(cpInfoVo)) {
			return ResultBean.error(MessageCodes.get(MessageCodes.M980014));
		}
		CpInfo cpInfo = new CpInfo();
		BeanUtils.copyProperties(cpInfoVo, cpInfo);
		cpInfoService.save(cpInfo);
		return ResultBean.ok();
	}

	/**
	 * 删除版权所属cp
	 *
	 * @param ids id主键拼接字符串,以英文逗号分隔
	 * @return resultbean
	 */
	@ApiOperation(value = "版权所属cp 删除", notes = "删除版权所属cp")
	@ApiImplicitParam(name = "ids", required = true, dataType = "String", value = "删除版权所属cp,主键id拼接字符串,以英文逗号分隔")
	@DeleteMapping(value = "/del")
	public ResultBean delete(String ids) {
		if (StringUtils.isNotBlank(ids)) {
			String[] idArray = ids.split(",");
			List<Long> idList = Arrays.stream(idArray).distinct().map(Long::parseLong).collect(Collectors.toList());
			cpInfoService.deleteByIds(idList);
		}
		return ResultBean.ok();
	}

	/**
	 * 导出
	 *
	 * @param response http响应
	 * @return excel
	 * @throws IOException 异常
	 */
	@ApiOperation(value = "版权所属cp 导出", notes = "导出版权所属cpexcel文件")
	@PostMapping(value = "/export")
	public ResultBean exportCpInfo(CpInfoVo cpInfoVo,
								   @RequestParam(defaultValue = "id") String sidx,
								   @RequestParam(defaultValue = "desc") String sord,
								   HttpServletResponse response) {
		ExportExcel exportExcel = new ExportExcel("cp数据导出", CpInfoPojo.class, 1);
		CpInfo condition = new CpInfo();
		BeanUtils.copyProperties(cpInfoVo,condition);
		List<CpInfo> lists = cpInfoService.findAll(condition,sidx,sord);
		List<CpInfoPojo> pojos = lists.stream().map(cpinfo -> {
			CpInfoPojo cpInfoPojo = new CpInfoPojo();
			cpInfoPojo.setCpId(String.valueOf(cpinfo.getCpId()));
			cpInfoPojo.setCpName(cpinfo.getCpName());
			return cpInfoPojo;
		}).collect(Collectors.toList());
		try {
			exportExcel.setDataList(pojos);
			exportExcel.write(response, "cpInfo_"+ LocalDateTimeUtils.localDateFormat(LocalDateTime.now(), "yy-MM-dd HH:mm:ss") + ".xlsx");
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
		}
		return ResultBean.ok();
	}

	/**
	 * 导入
	 *
	 * @param file excel文件
	 * @return resultbean
	 */
	@ApiOperation(value = "版权所属cp 导入", notes = "导入版权所属cpexcel文件")
	@PostMapping(value = "/import")
	public ResultBean importCpInfo(MultipartFile file) {
		StringBuffer msg = new StringBuffer("导入数据总数->");
		StringBuffer errMessage = new StringBuffer(".错误原因是->");
		AtomicInteger errNum = new AtomicInteger();// 全局错误数
		List<CpInfoPojo> list = new ArrayList<>();
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<CpInfoPojo> dataList = ei.getDataList(CpInfoPojo.class);
			if (CollectionUtil.isNotEmpty(dataList)) {
				msg.append(dataList.size() + ".错误数据数->");
				dataList.forEach(v -> importData(errMessage, errNum, v, list));
			} else {
				return ResultBean.error(MessageCodes.get(MessageCodes.M980205));
			}

			if (CollectionUtil.isNotEmpty(list)) {
				for (CpInfoPojo pojo : list) {
					CpInfo cpInfo = new CpInfo();
					cpInfo.setCpId(Long.valueOf(pojo.getCpId()));
					cpInfo.setCpName(pojo.getCpName());
					cpInfoService.save(cpInfo);
				}
			}
			msg.append(errNum);
			msg.append(errMessage);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultBean.error(MessageCodes.get(MessageCodes.M980000));
		}
		if (errNum.get() > 0) {
			return ResultBean.error(msg.toString().replace("[", "").replace("]", "").replace("[]", "").replace("!", ""));
		}
		return ResultBean.ok();
	}


	@GetMapping(value = "/get-all-cps")
	@ResponseBody
	public ResultBean getAllCps(){
		List<CpInfo> list=cpInfoService.findAll();
		return ResultBean.ok(list);
	}

	public void importData(StringBuffer errMessage, AtomicInteger errNum, CpInfoPojo pojo, List<CpInfoPojo> list) {
		if (pojo != null) {
			Boolean flag = true;
			List<String> messageList = ValidateFilter.getFilterMessage(pojo, Constants.VALIDATE_DEFAULT);
			flag = checkData(errMessage, errNum, pojo, flag, messageList,list);

			if (flag) {
				list.add(pojo);
			}
		}
	}

	public Boolean checkData(StringBuffer errMessage, AtomicInteger errNum, CpInfoPojo pojo, Boolean flag, List<String> messageList, List<CpInfoPojo> list) {
		if (flag && !messageList.isEmpty()) {
			errNum.addAndGet(1);
			flag = false;
			errMessage.append("导入出错：" + messageList.toString() + ".  ");
		}
		if (flag) {//如果已经传入的list里有重复的id或者cpname 也拒绝
			List<CpInfoPojo> data = list.stream().filter(cpInfoPojo ->
					cpInfoPojo.getCpId().equals(pojo.getCpId()) || cpInfoPojo.getCpName().equals(pojo.getCpName()))
					.collect(Collectors.toList());
			if(data.size()>0){
				errNum.addAndGet(1);
				flag = false;
				errMessage.append("cp编号：" + pojo.getCpId() + " cp名称：" + pojo.getCpName() + " 导入出错：" + MessageCodes.get(MessageCodes.M980014) + ".  ");
				return flag;
			}

			CpInfoVo cpInfoVo = new CpInfoVo();
			cpInfoVo.setCpName(pojo.getCpName());
			cpInfoVo.setCpId(Long.valueOf(pojo.getCpId()));

			if (isRepeat(cpInfoVo)) {
				errNum.addAndGet(1);
				flag = false;
				errMessage.append("cp编号：" + cpInfoVo.getCpId() + " cp名称：" + cpInfoVo.getCpName() + " 导入出错：" + MessageCodes.get(MessageCodes.M980014) + ".  ");
			}
		}
		return flag;
	}

	public Boolean isRepeat(CpInfoVo cpInfoVo) {
		CpInfo temp = new CpInfo();
		temp.setCpName(cpInfoVo.getCpName());
		Optional<CpInfo> opt = cpInfoService.findOne(Example.of(temp));
		if (opt.isPresent()) {
			CpInfo cpInfo = opt.get();
			if (cpInfoVo.getId() != null && !cpInfo.getId().equals(cpInfoVo.getId())) {
				return true;
			}
			if (cpInfoVo.getId() == null) {
				return true;
			}
		}
		if(cpInfoVo.getId() == null){
			CpInfo temp1 = new CpInfo();
			temp1.setCpId(cpInfoVo.getCpId());
			Optional<CpInfo> opt1 = cpInfoService.findOne(Example.of(temp1));
			if(opt1.isPresent()){
				return true;
			}
		}
		return false;
	}

}
